//
//  FavoriteViewController.m
//  PCNews
//
//  Created by PengchengWang on 16/3/5.
//  Copyright © 2016年 pengchengWang. All rights reserved.
//

#import "FavoriteViewController.h"
#import "NewsTableViewCell.h"
#import "AppDelegate.h"
#import "NewsViewController.h"
#import "SendValue.h"
#import "BaseModel.h"
#import <FMDB.h>
#import "DetailViewController.h"


@interface FavoriteViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UITableView *tableV;
@property (nonatomic, strong) Class myClass;
@property(nonatomic,strong)NSMutableArray *arrAllData;
@property(nonatomic,assign,getter=isEditTableView)BOOL editTableView;


@end

@implementation FavoriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.editTableView = NO;
    [self dataBound];
    [self setViews];
    self.myClass = [SendValue shareInstance].myclass;
    self.myClass = self.myClass?self.myClass:[NewsViewController class];
}

-(void)viewWillAppear:(BOOL)animated{
    [self dataBound];
    [self setViews];
}

-(void)dataBound{
    self.arrAllData = [[NSMutableArray alloc]init];
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //通过指定SQLite数据库文件路径来创建FMDatabase对象
    NSString *fileName = [doc stringByAppendingPathComponent:@"t_userCollect.sqlite"];
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"SELECT model FROM t_userCollect"];
        //遍历结果
        while ([resultSet next]) {
            NSData *modelData = [resultSet dataForColumn:@"model"];
            BaseModel  *baseModel = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];
            [self.arrAllData addObject:baseModel];
        }
        //关闭
        [resultSet close];
    }];
    [self.mbPreHUD hide:YES];
    [self.tableV reloadData];
}

-(void)setViews{
    UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"detial_buttom_back"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftBtnAction)];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightBtnAction)];
    if (self.isEditTableView) {
        [rightBarBtn setTitle:@"完成"];
    }
    self.navigationItem.leftBarButtonItem = leftBarBtn;
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
}

-(void)leftBtnAction{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    DrawerViewController *drawer = app.draw;
    id newsVC = [self.myClass new];
    UINavigationController *news_naVC = [[UINavigationController alloc]initWithRootViewController:newsVC];
    [news_naVC.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbar_bg_7"] forBarMetrics:UIBarMetricsDefault];
    [drawer setRootViewController:news_naVC];
}

-(void)rightBtnAction{
    self.editTableView = !self.editTableView;
    if (self.isEditTableView) {
        [self setEditing:YES animated:YES];
        
    }else{
        [self setEditing:NO animated:YES];
    }
    [self setViews];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrAllData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FavoriteTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"FavoriteTableViewCell"];
    }
    BaseModel *model = self.arrAllData[indexPath.row];
    cell.textLabel.text = model.title;
    cell.textLabel.font = [UIFont systemFontOfSize:20];
    NSDateFormatter *postDateFormatter = [[NSDateFormatter alloc]init];
    [postDateFormatter setDateFormat:@"yyyy/M/d HH:mm:ss"];
    NSDate *postDate = [postDateFormatter dateFromString:model.postdate];
    NSDate *currentDate = [NSDate date];
    NSTimeInterval currentInterval = [currentDate timeIntervalSinceDate:postDate];
    NSTimeInterval dayInterval = 12*60*60;
    NSTimeInterval hourInterval = 60*60;
    NSMutableString *strEditorPostDate = model.editor.mutableCopy;
    if (currentInterval>dayInterval) {
        currentInterval = currentInterval/dayInterval;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f天前",currentInterval]];
    }else if (currentInterval>hourInterval && currentInterval<dayInterval){
        currentInterval = currentInterval/hourInterval;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f小时前",currentInterval]];
    }else{
        currentInterval = currentInterval/60;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f分钟前",currentInterval]];
    }
    cell.detailTextLabel.text = strEditorPostDate;
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseModel *model = self.arrAllData[indexPath.row];
    DetailViewController *detailVC = [[DetailViewController alloc]initWithModel:model];
    [self.navigationController pushViewController:detailVC animated:YES];
}

/*
 删除收藏
 */
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    //先调用父类此方法
    [super setEditing:editing animated:animated];
    //编辑tableView第一步:设置为编辑状态,设置tableView是否可以编辑
    [self.tableV setEditing:editing animated:animated];
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    //返回编辑类型
    return UITableViewCellEditingStyleDelete;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    //删除
    BaseModel *model = self.arrAllData[indexPath.row];
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //通过指定SQLite数据库文件路径来创建FMDatabase对象
    NSString *fileName = [doc stringByAppendingPathComponent:@"t_userCollect.sqlite"];
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"DELETE FROM t_userCollect WHERE title = ?",model.title];
    }];
    [self dataBound];
    [self setViews];
}

-(UITableView *)tableV{
    if (!_tableV) {
        _tableV = [[UITableView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_tableV];
        _tableV.delegate = self;
        _tableV.dataSource = self;
    }
    return _tableV;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
